

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>rfml.nn.eval.confusion &mdash; RFML w/ PyTorch Software Documentation 1.0.0 documentation</title>
  

  
  
  
  

  
  <script type="text/javascript" src="../../../../_static/js/modernizr.min.js"></script>
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../../../" src="../../../../_static/documentation_options.js"></script>
        <script type="text/javascript" src="../../../../_static/jquery.js"></script>
        <script type="text/javascript" src="../../../../_static/underscore.js"></script>
        <script type="text/javascript" src="../../../../_static/doctools.js"></script>
        <script type="text/javascript" src="../../../../_static/language_data.js"></script>
        <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    
    <script type="text/javascript" src="../../../../_static/js/theme.js"></script>

    

  
  <link rel="stylesheet" href="../../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../../../index.html" class="icon icon-home"> RFML w/ PyTorch Software Documentation
          

          
          </a>

          
            
            
              <div class="version">
                1.0.0
              </div>
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <p class="caption"><span class="caption-text">Contents:</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../data.html"> Data</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../nbutils.html"> Notebook Utilities</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../nn.html"> Neural Networks</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../ptradio.html"> PyTorch Radio</a></li>
</ul>

            
          
        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../../../index.html">RFML w/ PyTorch Software Documentation</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../../../index.html">Docs</a> &raquo;</li>
        
          <li><a href="../../../index.html">Module code</a> &raquo;</li>
        
      <li>rfml.nn.eval.confusion</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <h1>Source code for rfml.nn.eval.confusion</h1><div class="highlight"><pre>
<span></span><span class="sd">&quot;&quot;&quot;Helper function for computing the confusion matrix of a model on a dataset.</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="n">__author__</span> <span class="o">=</span> <span class="s2">&quot;Bryse Flowers &lt;brysef@vt.edu&gt;&quot;</span>

<span class="c1"># External Includes</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
<span class="kn">from</span> <span class="nn">torch.utils.data</span> <span class="k">import</span> <span class="n">DataLoader</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">List</span><span class="p">,</span> <span class="n">Tuple</span>

<span class="c1"># Internal Includes</span>
<span class="kn">from</span> <span class="nn">rfml.data</span> <span class="k">import</span> <span class="n">Dataset</span><span class="p">,</span> <span class="n">Encoder</span>
<span class="kn">from</span> <span class="nn">rfml.nn.model</span> <span class="k">import</span> <span class="n">Model</span>


<div class="viewcode-block" id="compute_confusion"><a class="viewcode-back" href="../../../../nn.html#rfml.nn.eval.confusion.compute_confusion">[docs]</a><span class="k">def</span> <span class="nf">compute_confusion</span><span class="p">(</span>
    <span class="n">model</span><span class="p">:</span> <span class="n">Model</span><span class="p">,</span>
    <span class="n">data</span><span class="p">:</span> <span class="n">Dataset</span><span class="p">,</span>
    <span class="n">le</span><span class="p">:</span> <span class="n">Encoder</span><span class="p">,</span>
    <span class="n">batch_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">512</span><span class="p">,</span>
    <span class="n">mask</span><span class="p">:</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="o">.</span><span class="n">mask</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
<span class="p">)</span> <span class="o">-&gt;</span> <span class="n">np</span><span class="o">.</span><span class="n">ndarray</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;Compute and normalize a confusion matrix of this model on the dataset.</span>

<span class="sd">    Args:</span>
<span class="sd">        model (Model): (Trained) model to evaluate.</span>
<span class="sd">        data (Dataset): (Testing) data to use for evaluation.</span>
<span class="sd">        le (Encoder): Mapping from human readable to machine readable.</span>
<span class="sd">        batch_size (int, optional): Defaults to 512.</span>
<span class="sd">        mask (pd.DataFrame.mask, optional): Mask to apply to the data before computing</span>
<span class="sd">                                            accuracy.  Defaults to None.</span>

<span class="sd">    Returns:</span>
<span class="sd">        np.ndarray: Normalized Confusion Matrix</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">predictions</span><span class="p">,</span> <span class="n">labels</span> <span class="o">=</span> <span class="n">_extract_predictions_and_labels</span><span class="p">(</span>
        <span class="n">model</span><span class="o">=</span><span class="n">model</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">data</span><span class="p">,</span> <span class="n">le</span><span class="o">=</span><span class="n">le</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="n">batch_size</span><span class="p">,</span> <span class="n">mask</span><span class="o">=</span><span class="n">mask</span>
    <span class="p">)</span>
    <span class="k">return</span> <span class="n">_confusion_matrix</span><span class="p">(</span><span class="n">predictions</span><span class="o">=</span><span class="n">predictions</span><span class="p">,</span> <span class="n">labels</span><span class="o">=</span><span class="n">labels</span><span class="p">,</span> <span class="n">le</span><span class="o">=</span><span class="n">le</span><span class="p">)</span></div>


<span class="k">def</span> <span class="nf">_confusion_matrix</span><span class="p">(</span>
    <span class="n">predictions</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">int</span><span class="p">],</span> <span class="n">labels</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">int</span><span class="p">],</span> <span class="n">le</span><span class="p">:</span> <span class="n">Encoder</span>
<span class="p">)</span> <span class="o">-&gt;</span> <span class="n">np</span><span class="o">.</span><span class="n">ndarray</span><span class="p">:</span>
    <span class="c1"># Note: This could be replaced with sklearn.metrics.confusion_matrix</span>
    <span class="c1"># It is simply rewritten in order to avoid introducing a dependency for one thing</span>
    <span class="n">confusion_matrix</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">([</span><span class="nb">len</span><span class="p">(</span><span class="n">le</span><span class="o">.</span><span class="n">labels</span><span class="p">),</span> <span class="nb">len</span><span class="p">(</span><span class="n">le</span><span class="o">.</span><span class="n">labels</span><span class="p">)])</span>

    <span class="c1"># Compute the total number of predictions</span>
    <span class="k">for</span> <span class="n">predicted_label</span><span class="p">,</span> <span class="n">true_label</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">predictions</span><span class="p">,</span> <span class="n">labels</span><span class="p">):</span>
        <span class="n">confusion_matrix</span><span class="p">[</span><span class="n">true_label</span><span class="p">,</span> <span class="n">predicted_label</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span>
            <span class="n">confusion_matrix</span><span class="p">[</span><span class="n">true_label</span><span class="p">,</span> <span class="n">predicted_label</span><span class="p">]</span> <span class="o">+</span> <span class="mf">1.0</span>
        <span class="p">)</span>

    <span class="c1"># Normalize these predictions to be a percentage</span>
    <span class="k">for</span> <span class="n">true_label</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">confusion_matrix</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">]):</span>
        <span class="c1"># Avoid a divide by zero case, no guarantee that we are calling this method</span>
        <span class="c1"># with data for all of the classes that could be predicted</span>
        <span class="n">total</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">confusion_matrix</span><span class="p">[</span><span class="n">true_label</span><span class="p">,</span> <span class="p">:])</span>

        <span class="k">if</span> <span class="n">total</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
            <span class="n">confusion_matrix</span><span class="p">[</span><span class="n">true_label</span><span class="p">,</span> <span class="p">:]</span> <span class="o">=</span> <span class="mf">0.0</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">confusion_matrix</span><span class="p">[</span><span class="n">true_label</span><span class="p">,</span> <span class="p">:]</span> <span class="o">=</span> <span class="n">confusion_matrix</span><span class="p">[</span><span class="n">true_label</span><span class="p">,</span> <span class="p">:]</span> <span class="o">/</span> <span class="n">total</span>

    <span class="k">return</span> <span class="n">confusion_matrix</span>


<span class="k">def</span> <span class="nf">_extract_predictions_and_labels</span><span class="p">(</span>
    <span class="n">model</span><span class="p">:</span> <span class="n">Model</span><span class="p">,</span>
    <span class="n">data</span><span class="p">:</span> <span class="n">Dataset</span><span class="p">,</span>
    <span class="n">le</span><span class="p">:</span> <span class="n">Encoder</span><span class="p">,</span>
    <span class="n">batch_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">512</span><span class="p">,</span>
    <span class="n">mask</span><span class="p">:</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="o">.</span><span class="n">mask</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
<span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Tuple</span><span class="p">[</span><span class="n">List</span><span class="p">[</span><span class="nb">int</span><span class="p">],</span> <span class="n">List</span><span class="p">[</span><span class="nb">int</span><span class="p">]]:</span>
    <span class="n">ret_predictions</span><span class="p">,</span> <span class="n">ret_labels</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(),</span> <span class="nb">list</span><span class="p">()</span>
    <span class="n">dl</span> <span class="o">=</span> <span class="n">DataLoader</span><span class="p">(</span>
        <span class="n">data</span><span class="o">.</span><span class="n">as_torch</span><span class="p">(</span><span class="n">le</span><span class="o">=</span><span class="n">le</span><span class="p">,</span> <span class="n">mask</span><span class="o">=</span><span class="n">mask</span><span class="p">),</span> <span class="n">shuffle</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="n">batch_size</span>
    <span class="p">)</span>

    <span class="k">for</span> <span class="n">_</span><span class="p">,</span> <span class="n">data</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">dl</span><span class="p">):</span>
        <span class="n">inputs</span><span class="p">,</span> <span class="n">labels</span> <span class="o">=</span> <span class="n">data</span>
        <span class="n">predictions</span> <span class="o">=</span> <span class="n">model</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
        <span class="n">ret_predictions</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">predictions</span><span class="p">)</span>
        <span class="n">ret_labels</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">labels</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">ret_predictions</span><span class="p">,</span> <span class="n">ret_labels</span>
</pre></div>

           </div>
           
          </div>
          <footer>
  

  <hr/>

  <div role="contentinfo">
    <p>
        &copy; Copyright 2019, Bryse Flowers

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  


  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
   

</body>
</html>